<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['mes:pro:workorder:export']"
        >
          导出
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-video-play"
            size="mini"
            @click="checkStock"
            v-hasPermi="['mes:pro:workorder:check']"
        >
          缺失物料检测
        </el-button>
      </el-col>
      <right-toolbar @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
        ref="table"
        v-loading="loading"
        :data="workorderbomList"
        @selection-change="handleSelectionChange"
        :row-class-name="stockStatus"
        @expand-change="handleExpandChange"
    >
      <!--        :row-class-name="getRowClassName"-->
      <!-- 控制展开行按钮的显示 -->
<!--    <template slot-scope="showRows">-->
      <el-table-column type="expand" width="30" v-if="shouldShowExpandColumn" >
        <template slot-scope="props">
          <div v-if="props.row.multiFlag === 'Y' && props.row.alternativeMdItems && props.row.alternativeMdItems.length > 0">
            <el-table
                :data="props.row.alternativeMdItems"
                style="width: 100%"
                :row-class-name="stockStatus"
            >
              <el-table-column label="物料编号" width="120" align="center">
                <template slot-scope="innerScope">
                  <el-radio
                      v-model="props.row.selectedAlternative"
                      :label="innerScope.row.itemCode"
                      @change="handleRadioChange(props.row, innerScope.row)"
                      @click.native.stop
                      :disabled="optType === 'view'"
                  >
                    {{ innerScope.row.itemCode }}
                  </el-radio>
                </template>
              </el-table-column>
              <el-table-column label="物料名称" prop="itemName" align="center" />
              <el-table-column label="规格型号" prop="itemSpc" align="center" />
              <el-table-column label="单位" prop="unitOfMeasure" align="center" />
              <el-table-column label="预计使用量" align="center" prop="quantity" />
              <el-table-column label="库存量" align="center" prop="quantityOnhand" />
            </el-table>
          </div>
        </template>
      </el-table-column>
<!--    </template>-->


      <el-table-column type="selection" width="55" align="center"   />
      <el-table-column label="BOM物料编号" width="120" align="center" prop="itemCode" />
      <el-table-column label="BOM物料名称" width="200" align="center" prop="itemName" :show-overflow-tooltip="true" />
      <el-table-column label="一码多料类型" min-width="120" align="left" key="multiFlag" prop="multiFlag" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.item_multi_flag" :value="scope.row.multiFlag" />
        </template>
      </el-table-column>
      <el-table-column label="规格型号" align="center" prop="itemSpc" :show-overflow-tooltip="true" />
      <el-table-column label="单位" align="center" prop="unitOfMeasure" />
      <el-table-column label="物料/产品" align="center" prop="itemOrProduct">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_item_product" :value="scope.row.itemOrProduct" />
        </template>
      </el-table-column>
      <el-table-column label="预计使用量" align="center" prop="quantity" />
      <el-table-column label="库存量" align="center" prop="quantityOnhand">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p align="center">{{ scope.row.quantityStatus }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="small">{{ scope.row.quantityOnhand }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-if="workorder.status == 'PREPARE'"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['mes:pro:workorder:edit']"
              :disabled="optType==='view'">
            修改
          </el-button>
<!--          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleAddSubWorkorder(scope.row)"
              v-if="workorder.status == 'CONFIRMED' && scope.row.itemOrProduct == 'PRODUCT' && workorder.workorderType == 'SELF'"
              v-hasPermi="['mes:pro:workorder:edit']"
          >
            生成工单
          </el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="预计使用量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入预计使用量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWorkorderbom, getWorkorderbom, delWorkorderbom, addWorkorderbom, updateWorkorderbom, updateMultiWorkorderbom } from "@/api/mes/pro/workorderbom";
import{convertPurchaseRequest} from "@/api/mes/pro/workorder";

import{initItemrecpt} from "@/api/mes/wm/itemrecpt";
import { stockCheck} from "@/api/mes/pro/workorder";
export default {
  name: "Workorderbom",
  dicts: ['mes_item_product', 'item_multi_flag'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产工单BOM组成表格数据
      workorderbomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workorderId: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        itemSpc: null,
        unitOfMeasure: null,
        itemOrProduct: null,
        quantity: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        workorderId: [
          { required: true, message: "生产工单ID不能为空", trigger: "blur" }
        ],
        itemId: [
          { required: true, message: "BOM物料ID不能为空", trigger: "blur" }
        ],
        itemCode: [
          { required: true, message: "BOM物料编号不能为空", trigger: "blur" }
        ],
        itemName: [
          { required: true, message: "BOM物料名称不能为空", trigger: "blur" }
        ],
        unitOfMeasure: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
        itemOrProduct: [
          { required: true, message: "物料产品标识不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "预计使用量不能为空", trigger: "blur" }
        ],
      }
    };
  },
  computed: {
    shouldShowExpandColumn() {
      // 检查是否有任何行的 multiFlag 为 'Y'
      return this.workorderbomList.some(row => row.multiFlag === 'Y');
    }
  },
  props: {
    optType: undefined,
    workorder: undefined,
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询生产工单BOM组成列表 */
    getList() {
      this.loading = true;
      this.queryParams.workorderId = this.workorder.workorderId;
      listWorkorderbom(this.queryParams).then(response => {
        const rows = response.rows;
        this.workorderbomList = rows.map(row => {
          const newRow = { ...row };
          newRow.selectedAlternative = '';

          if (row.alternativeMdItems) {
            newRow.alternativeMdItems = row.alternativeMdItems.map(item => {
              const newItem = { ...item };
              newItem.isSelected = item.selectedCode === 'Y';
              if (item.selectedCode === 'Y') {
                newRow.selectedAlternative = item.itemCode;
              }
              return newItem;
            });
          }

          return newRow;
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    getList1(response) {
      this.loading = true;
      // this.queryParams.workorderId = this.workorder.workorderId;
      // listWorkorderbom(this.queryParams).then(response => {
        const rows = response.rows;
        this.workorderbomList = rows.map(row => {
          const newRow = { ...row };
          newRow.selectedAlternative = '';

          if (row.alternativeMdItems) {
            newRow.alternativeMdItems = row.alternativeMdItems.map(item => {
              const newItem = { ...item };
              newItem.isSelected = item.selectedCode === 'Y';
              if (item.selectedCode === 'Y') {
                newRow.selectedAlternative = item.itemCode;
              }
              return newItem;
            });
          }

          return newRow;
        });
        this.total = response.total;
        this.loading = false;
      // });
    },
    /** 库存状态改变行颜色 */
    stockStatus(data, rowIndex) {
      if (data.row.quantity > data.row.quantityOnhand) {
        data.row.quantityStatus = "库存不足";
        return "warning-row";
      } else if (this.isEmpty(data.row.quantityOnhand)) {
        data.row.quantityStatus = "";
      } else {
        data.row.quantityStatus = "库存充足";
      }
      // if (data.row.isSelected) {
      //   return 'selected-row';
      // }
      // return '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        lineId: null,
        workorderId: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        itemSpc: null,
        unitOfMeasure: null,
        itemOrProduct: null,
        quantity: null,
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lineId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lineId = row.lineId || this.ids;
      getWorkorderbom(lineId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改生产工单BOM组成";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.lineId != null) {
            updateWorkorderbom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWorkorderbom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleAddSubWorkorder(row) {
      var temp = JSON.parse(JSON.stringify(this.workorder));
      temp.workorderCode = null;
      temp.workorderName = row.itemName + "【" + row.quantity + "】" + row.unitOfMeasure;
      temp.productId = row.itemId;
      temp.productCode = row.itemCode;
      temp.productName = row.itemName;
      temp.unitOfMeasure = row.unitOfMeasure;
      temp.quantity = row.quantity;
      temp.status = 'PREPARE';
      this.$emit('handleAddSub', temp);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/pro/workorderbom/export', {
        ...this.queryParams
      }, `workorderbom_${new Date().getTime()}.xlsx`);
    },
    checkStock() {
      // this.$modal.alert("检测库存");
      // this.queryParams.workorderId = this.workorder.workorderId;
      let that = this; // 保存对`this`的引用
      this.form.workorderId=this.workorder.workorderId;
      stockCheck(this.form).then(
          response=>{
            if(response.enoughFlag==false){
              // this.$modal.msgWarning(response.msg);
              this.$modal.confirm('库存不足,是否生成采购申请单？【确认后将不能更改】').then(function () {
                // that.form.status = 'CONFIRMED';
                // that.submitForm();
                console.log('生成采购申请单---');
                console.log('form0---',that.form);
                that.form.workorderId=that.workorder.workorderId;
                console.log('form1---',that.form);
                convertPurchaseRequest(that.form).then(
                    response=>{
/*                      let recptCode = response.data.recptCode;
                      console.log('recptCode---',recptCode);
                      let msg = `生成入库工单成功,入库单编号:${recptCode},是否跳转到入库工单页面?`
                      this.open = false;
                      this.$modal.confirm(msg)
                          .then(() => {
                            // 跳转到生产工单页面
                            this.$router.push({ path: '/mes/mes/wm/itemrecpt' });
                          });*/
                      console.log('采购成功----00',this);
                      that.$modal.alertSuccess('生成采购申请单成功');
                    }
                )
                // initItemrecpt(that.form);
                console.log('跳转到采购申请单');
              });
              return false;
            }else{
              this.$modal.msgSuccess("物料充足");
            }

            // 进一步的处理逻辑
          }
      );
    },
    /** 内层表格单选按钮变化事件 */
    handleRadioChange(mainRow, innerRow) {
      console.log(' handleRadioChange  ----mainRow---',mainRow);
      console.log(' handleRadioChange  ----innerRow---',innerRow);
      mainRow.selectedAlternative = innerRow.itemCode;
      mainRow.alternativeMdItems.forEach(item => {
        item.isSelected = item.itemCode === innerRow.itemCode;
      });
      this.form = innerRow;
      this.form.workorderId = this.workorder.workorderId;
      this.form.bomVersion=mainRow.bomVersion;
      this.form.bomVersionId=mainRow.bomVersionId;
      updateMultiWorkorderbom(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      });
    },
    /** 获取行类名 */
    getRowClassName({ row }) {
      if (row.isSelected) {
        return 'selected-row';
      }
      return '';
    },
    /** 监听展开行变化事件 */
    handleExpandChange(row, expandedRows) {
      if (expandedRows.includes(row)) {
        this.$refs.table.toggleRowExpansion(row, true);
      } else {
        this.$refs.table.toggleRowExpansion(row, false);
      }
    }
  }
};
</script>

<style scoped>
.warning-row {
  background: oldlace;
}
</style>
